package com.lzx.adx.report.support.strategy.media;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.annnotions.MediaType;
import com.lzx.adx.report.constant.MediaChannelConstant;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.model.common.CommonReportRequest;
import com.lzx.adx.report.model.wifi.WifiRequest;
import com.lzx.adx.report.util.UrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@MediaType(MediaChannelConstant.WIFI)
public class WifiCallBackStrategy extends AbstractCallback{

    @Override
    public ResponseEntity callback(ReportDTO reportDTO, AccountDTO accountDTO, String callType, String ts) {
        String requestId=reportDTO.getBizRequestId();
        boolean base = base(reportDTO, accountDTO, callType, ts);
        if(!base){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String eventType = jsonObject.getString(callType);


        log.info("账号id{},请求id{} wifi的", reportDTO.getDspId(), requestId);
        CommonReportRequest reportRequest = JsonUtils.parseObject(reportDTO.getExtend(), CommonReportRequest.class);
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("cid", reportRequest.getContentId());
        paramsReq.put("sid", reportRequest.getSid());
        paramsReq.put("stime", reportRequest.getTraceTime());
        paramsReq.put("os", reportRequest.getOs());
        paramsReq.put("idfa", reportRequest.getIdfa());
        paramsReq.put("imei", reportRequest.getImeiSum());
        paramsReq.put("clientid", jsonObject.getString("clientid"));
        paramsReq.put("ts", System.currentTimeMillis() / 1000);
        paramsReq.put("event_type", eventType);
        //将参数转换 进行排序转换为url
        String urlParams = UrlUtil.covertParamsOrderByAsc(paramsReq);
        String finalResultUrl = accountDTO.getSspApiUrl() + "?" + urlParams;
        String sign = StringUtils.upperCase(SecureUtil.md5(finalResultUrl + accountDTO.getSspKey()));
        String resultUrl = UrlUtil.handMeitu(finalResultUrl, sign);
        log.info("账号id{},请求id{} 给wifi上报回传完整的地址：{}", reportDTO.getDspId(), requestId, resultUrl);
        HttpRequest body = HttpUtil.createGet(resultUrl);
        String result = body.execute().body();
        log.info("账号id{},请求id{} 给wifi上报回传结果为 {}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }
}
